package com.empire.devops.emops.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Objects;

/**
 * Es搜索引擎客戶端配置
 * @author auron.xu
 */
@Configuration
public class ElasticSearchRestClient {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchRestClient.class);

    /**
     * 使用冒号隔开ip和端口
     */
    @Value("${elasticSearch.ip}")
    String[] ipAddress;
    /**
     * ip:port切分后数组长度
     */
    private static final int ADDRESS_LENGTH = 2;
    /**
     * HTTP_HOST的scheme
     */
    private static final String HTTP_SCHEME = "http";

    /**
     * Es lowLevelClient构建器
     * @return
     */
    @Bean
    public RestClientBuilder restClientBuilder() {
        HttpHost[] hosts =
            Arrays.stream(ipAddress).map(this::makeHttpHost).filter(Objects::nonNull).toArray(HttpHost[]::new);
        logger.debug("hosts:{}", Arrays.toString(hosts));
        return RestClient.builder(hosts);
    }

    /**
     * 声明RestClient对象
     * @param restClientBuilder Es lowLevelClient构建器
     * @return Es客户端RestClient
     */
    @Bean(name = "lowLevelClient")
    public RestClient lowLevelClient(@Autowired RestClientBuilder restClientBuilder) {
        return restClientBuilder.build();
    }

    /**
     * 声明RestHighLevelClient对象
     * @param restClientBuilder Es lowLevelClient构建器
     * @return Es客户端RestHighLevelClient
     */
    @Bean(name = "highLevelClient")
    public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
        return new RestHighLevelClient(restClientBuilder);
    }

    /**
     * 将hosts字符串转换成HttpHost
     * @param hosts ip:port
     * @return HttpHost
     */
    private HttpHost makeHttpHost(String hosts) {
        assert StringUtils.hasLength(hosts);
        String[] address = hosts.split(":");
        if (address.length == ADDRESS_LENGTH) {
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            return new HttpHost(ip, port, HTTP_SCHEME);
        } else {
            return null;
        }
    }
}
